var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxAddressModel = function (obj) {
    YjxBaseModel.call(this,obj);

    // `addr_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '地址id',
    // `base_id` bigint(20) NOT NULL COMMENT '拷贝源地址id',
    // `type` int(3) NOT NULL DEFAULT '0' COMMENT '地址类型：0用户地址管理, 1用户地址列表用, 10商品订单, 20发票订单',
    // `mobile` bigint(20) NOT NULL COMMENT '手机号',
    // `phone` bigint(20) DEFAULT NULL COMMENT '座机号',
    // `name` varchar(20) NOT NULL COMMENT '收货者',
    // `prov` bigint(20) DEFAULT NULL COMMENT '省会',
    // `city` bigint(20) DEFAULT NULL COMMENT '城市',
    // `dist` bigint(20) DEFAULT NULL COMMENT '区',
    // `detail` varchar(500) NOT NULL DEFAULT '' COMMENT '详细地址',
    // `user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
    // `default` int(1) NOT NULL DEFAULT '0' COMMENT '默认地址: 0否,1是',
    // `create_time` datetime NOT NULL,
    // `update_time` datetime NOT NULL,
    // `del_flg` int(1) NOT NULL DEFAULT '0',
    // PRIMARY KEY (`addr_id`),
    // KEY `Addr_idx_01` (`user_id`)

};

YjxAddressModel.prototype = new YjxBaseModel();

// 取得表名
YjxAddressModel.prototype.getTableName = function(){
    return 'yjx_address';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxAddressModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'addr_id='+this.addr_id;
};


// 根据用户id获取最新的用户地址信息
YjxAddressModel.prototype.getLastAddrByUserId = function(userId, callback){
    var THIS = this;

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxAddressModel.getLastAddrByUserId Err:'+err);
            return callback(err,null);
        }

        var sql = " SELECT t.*, a1.name as prov_name, a2.name as city_name, a3.name as dist_name "+
            ' FROM yjx.yjx_address t '+
            ' LEFT JOIN itbour.itb_area a1 ON t.prov = a1.id AND a1.del_flg=0 '+
            ' LEFT JOIN itbour.itb_area a2 ON t.city = a2.id AND a2.del_flg=0 '+
            ' LEFT JOIN itbour.itb_area a3 ON t.dist = a3.id AND a3.del_flg=0 '+
            " WHERE t.user_id="+userId+" AND t.del_flg=0 AND t.type=1 "+
            ' ORDER BY t.create_time DESC '+
            ' LIMIT 0,1 ';
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            console.log();
            if(error){
                console.log(error);
                return callback(error,null);
            }
            if(!results || results.length==0){
                return callback(null, null);
            }

            return callback(null, results[0]);
        });
    });
};

function sql_getAddrListByUser(bForCnt, userId, pageNum, pageSize){
    var sql = '';
    if(bForCnt) {
        sql += ' SELECT COUNT(*) AS count ';
    } else {
        sql += ' SELECT t.*, '+
            ' a1.name as prov_name, a2.name as city_name, a3.name as dist_name ';
    }

    sql +=
        ' FROM yjx.yjx_address t '+
        ' LEFT JOIN itbour.itb_area a1 ON t.prov = a1.id AND a1.del_flg=0 '+
        ' LEFT JOIN itbour.itb_area a2 ON t.city = a2.id AND a2.del_flg=0 '+
        ' LEFT JOIN itbour.itb_area a3 ON t.dist = a3.id AND a3.del_flg=0 '+
        ' WHERE t.del_flg=0 AND t.type=1 '+
        ' AND user_id='+userId ;

    if(!bForCnt){
        //排序
        var skipCnt = Number(pageNum||'0')*Number(pageSize||'0');
        sql += " ORDER BY t.default DESC, t.update_time DESC "+// 默认地址放前
            " LIMIT "+skipCnt+", "+Number(pageSize||'0');
    }
    return sql;
};

// 根据用户id获取地址列表
YjxAddressModel.prototype.getAddrListByUserId = function(userId, pageNum, pageSize, callback){
    var THIS = this;
    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxAddressModel.getAddrListByUserId Err:'+err);
            return callback(err,null);
        }

        var sql = sql_getAddrListByUser(false, userId, pageNum, pageSize);
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            console.log();
            if(error){
                console.log(error);
                return callback(error,null);
            }
            return callback(null, results);
        });
    });
};
YjxAddressModel.prototype.getAddrListByUserIdCnt = function(userId, callback){
    var THIS = this;
    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxAddressModel.getAddrListByUserIdCnt Err:'+err);
            return callback(err,null);
        }

        var sql = sql_getAddrListByUser(true, userId, null, null);
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            console.log();

            if(results && results.length > 0) {
                callback(error, results[0].count);
            }else {
                callback(error, 0);
            }
        });
    });
};

/**
 * 取消用户当前的默认地址
 *
 * @param userId 用户唯一标识
 * @param callback 更新回调
 *             error 如果更新失败, 为失败原因
 **/
YjxAddressModel.prototype.clearDefaultAddress = function(userId, callback) {
    var THIS = this;
    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxAddressModel.clearDefaultAddress Err:'+err);
            return callback(err,null);
        }

        var sql =
            " UPDATE yjx.yjx_address addr " +
            " SET addr.default=0, " +
            "     addr.update_by=" + userId + ',' +
            "     addr.update_time=sysdate() " +
            " WHERE addr.user_id=" + userId +
            "   AND addr.type=1 " +
            "   AND addr.default=1 " +
            "   AND addr.del_flg=0 " ;
        console.log(sql);
        connection.query(sql, function (error, result) {
            connection.release();
            console.log();
            return callback(error);
        });
    });
};



module.exports = YjxAddressModel;

